package com.wjd.gulimall.product.exception;

import com.wjd.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static com.wjd.common.exception.BizCodeEnum.UNKNOWN_EXCEPTION;
import static com.wjd.common.exception.BizCodeEnum.VALIDATION_EXCEPTION;

@Slf4j
@RestControllerAdvice(basePackages = "com.wjd.gulimall.product.controller")
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> fieldErrors = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String fieldName = error.getField();
            String errorMessage = error.getDefaultMessage() != null ? error.getDefaultMessage() : "Invalid value";
            fieldErrors.compute(fieldName, (key, value) -> value != null ? value + "; " + errorMessage : errorMessage);
        }
        log.debug("An validation occurred: {}", e.getMessage(), e);
        return R.error(VALIDATION_EXCEPTION.getCode(), VALIDATION_EXCEPTION.getMsg())
                .put("data", fieldErrors);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error("An error occurred: {}", e.getMessage(), e);
        return R.error(UNKNOWN_EXCEPTION.getCode(), UNKNOWN_EXCEPTION.getMsg())
                .put("data", e.getMessage());
    }

    /**
     * 处理所有未处理的异常
     */
    @ExceptionHandler(Throwable.class)
    public R handleThrowable(Throwable e) {
        log.error("An error occurred: {}", e.getMessage(), e);
        return R.error(UNKNOWN_EXCEPTION.getCode(), UNKNOWN_EXCEPTION.getMsg())
                .put("data", e.getMessage());
    }

}
